/*
 * TcpServer.h
 *
 *  Created on: Aug 12, 2016
 *      Author: ubuntu
 */

#ifndef TCPSERVER_H_
#define TCPSERVER_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <iostream>
#include <vector>
#include <list>

using namespace std;

typedef void (*ev)();

struct connectop {
	int fd;
	int epfd;
	void *ptr;
	int (*dispatch)(void *);
};

class ClientConnection;

class TcpServer {
public:
	TcpServer(int port, int type);
	virtual ~TcpServer();

	virtual bool init();
	virtual void start();
	virtual void stop();
	virtual void on_close(ClientConnection *);
	virtual void add(void *arg);
	virtual void del(void *arg);
	virtual void *find(void *arg);
	virtual void clearClient();
	static int on_accept(void *arg);
	static int on_read(void *arg);

	int getPort();

protected:
	virtual void run();
	virtual int do_accept();
	virtual ClientConnection *on_connect(struct connectop *, struct sockaddr *);

protected:
	int m_port;
	int m_fd;
	int m_type;
	int m_epfd;
	bool m_bTerminated;
	struct epoll_event *ep_ev;
	int event_cnt;
	struct connectop *m_op;

	list<ClientConnection *> m_lstClient;
};

#endif /* TCPSERVER_H_ */
